package com.njust.controller;

import com.njust.dao.EmployeeDao;
import com.njust.entity.Employee;
import com.njust.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

@Controller
public class EmployeeController {

    @Autowired
    EmployeeService employeeService;

    @GetMapping("/employees")
    public String allUser(Model model){
        List<Employee> employeeList = employeeService.getAllEmployee();
        model.addAttribute("employeeList", employeeList);
        return "userList.jsp";
    }

    /**
     * Post请求添加用户
     * @param request
     * @return
     */
    @PostMapping("/employee")
    public String addUser(HttpServletRequest request){
        System.out.println("执行POST方法");
        Employee employee = new Employee();
        employee.setLastName(request.getParameter("lastName"));
        employee.setEmail(request.getParameter("email"));
        employee.setGender(request.getParameter("gender"));
        employee.setDepartment(request.getParameter("department"));
        employeeService.saveEmployee(employee);
        return "redirect:/employees";
    }

    /**
     * PUT请求，修改用户
     * @param id
     * @param request
     * @return
     */
    @PutMapping("/employee/{id}")
    public String updateUser(@PathVariable Integer id, HttpServletRequest request){
        System.out.println("执行PUT方法");
        Employee employee = new Employee();
        if (id != null){
            employee.setId(id);
        }
        employee.setLastName(request.getParameter("lastName"));
        employee.setEmail(request.getParameter("email"));
        employee.setGender(request.getParameter("gender"));
        employee.setDepartment(request.getParameter("department"));
        employeeService.saveEmployee(employee);
        return "redirect:/employees";
    }

    /**
     * Delete请求删除用户
     * @param id
     * @return
     */
    @DeleteMapping("/employee/{id}")
    public String deleteUser(@PathVariable Integer id){
        employeeService.deleteEmployee(id);
        return "redirect:/employees";
    }

    /**
     * Get请求，获取用户信息
     * @param id
     * @param model
     * @return
     */
    @GetMapping("/employee/{id}")
    public String updateEmployee(@PathVariable int id, Model model){
        Employee employee = employeeService.getEmployee(id);
        model.addAttribute("employee", employee);
        model.addAttribute("departments", EmployeeDao.deparments);
        return "edit.jsp";
    }


    @RequestMapping("/toAddPage")
    public String toAddPage(Model model){
        model.addAttribute("departments", EmployeeDao.deparments);
        return "add.jsp";
    }
}
